package cn.gtv.sdk.dcas.api;

import android.content.Context;

import com.sad.jetpack.v1.datamodel.api.IDataModelObtainedCallback;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;
import com.sad.jetpack.v1.datamodel.api.IDataModelResponse;
import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.gtv.sdk.dcas.api.db.Event;

public class DCASTrackerImpl implements ITacker,ITacker.Builder{

    private JSONObject eventJson=new JSONObject();
    private JSONObject detailJson =new JSONObject();
    private Context context;
    private IServerTokenFactory serverTokenFactory= DCASCore.globalConfig.getServerTokenFactory();
    private IEncryptor encryptor;
    private DCASTrackerImpl(){}
    private DCASTrackerImpl(Context context){
        this.context=context;
        encryptor=new AESEncryptor(context);
    }
    public static ITacker.Builder newBuilder(Context context){
        return new DCASTrackerImpl(context);
    }

    @Override
    public JSONObject event() {
        return this.eventJson;
    }

    @Override
    public JSONObject detail() {
        return this.detailJson;
    }

    @Override
    public IServerTokenFactory serverTokenFactory() {
        return this.serverTokenFactory;
    }

    @Override
    public IEncryptor encryptor() {
        return this.encryptor;
    }

    @Override
    public ITacker submit() {
        try {
            List<Event> events=EventsManager.getInstance(context).getAll();
            if (!DCASCore.globalConfig.getRecorderStrategy().enableStorage(events)){
                LogcatUtils.e("----------->DCAS日志库存储策略不允许存储，当前条数："+events.size());
                return this;
            }
            if (serverTokenFactory!=null){
                serverTokenFactory.onCreateServerToken(new IServerTokenConsumer() {
                    @Override
                    public void optServerToken(String serverToken) {
                        JSONObject data=TrackerDataCreator.createTrackerData(context,serverToken,eventJson, detailJson);
                        if (encryptor!=null){
                            JSONObject info=data.optJSONObject("info");
                            String e_info=encryptor.encrypt(info.toString());
                            try {
                                data.put("info",e_info);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            LogcatUtils.e("----------->DCAS日志库执行插入："+data.toString(4));
                            EventsManager.getInstance(context).insert(data.toString());
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return this;
    }

    @Override
    public ITacker upload(boolean alreadySubmit) {
        List<Event> events=EventsManager.getInstance(context).getAll();
        if(events!=null && events.size()>0){
            boolean canUpload=true;
            if (!alreadySubmit){
                canUpload=true;
            }
            else {
                canUpload=!DCASCore.globalConfig.getRecorderStrategy().enableUpload(events);
                //这里需要注意，为了防止和insert监听回调onChange重复上传，这里如果达到上传条件，则由数据库监听去上传，这里就不再重复上传
            }
            if (canUpload){
                LogcatUtils.e("----------->DCAS开始上报(直接上报)："+events.size());
                if (DCASCore.isUploading(context)){
                    LogcatUtils.e("----------->DCAS上报中止：已经在上报了");
                    return this;
                }
                //立即删除数据已经消费完的数据，防止重复消费
                EventsManager.getInstance(context).deleteOldest(events.get(events.size() - 1).getUpdateTime());
                if(DCASCore.globalConfig.getServerTokenFactory()!=null){
                    DCASCore.globalConfig.getServerTokenFactory().onCreateServerToken(new IServerTokenConsumer() {
                        @Override
                        public void optServerToken(String serverToken) {
                            DCASDataUploaderImpl.newBuilder(context)
                                    .tag("track_data_upload")
                                    .callback(new IDataModelObtainedCallback() {
                                        @Override
                                        public void onDataObtainedCompleted(IDataModelResponse response) {
                                            //上传完毕
                                        }
                                    })
                                    .build()
                                    .postDCASDataToServer(events);
                        }
                    });
                }
            }

        }
        return this;
    }


    @Override
    public Builder toBuilder() {
        return this;
    }


    @Override
    public Builder event(JSONObject eventJson) {
        this.eventJson=eventJson;
        return this;
    }

    @Override
    public Builder event(String type, String target,String id) {
        try {
            this.eventJson.put("type",type);
            this.eventJson.put("target",target);
            this.eventJson.put("id",id);
        }catch (Exception e){
            e.printStackTrace();
        }

        return this;
    }

    @Override
    public Builder detail(JSONObject detailJson) {
        this.detailJson=detailJson;
        return this;
    }

    @Override
    public Builder serverTokenFactory(IServerTokenFactory serverTokenFactory) {
        this.serverTokenFactory=serverTokenFactory;
        return this;
    }

    @Override
    public Builder encryptor(IEncryptor encryptor) {
        return this;
    }


    @Override
    public ITacker build() {
        return this;
    }

}
